#!/usr/bin/env python
# -*- coding: UTF-8 -*-

#LOG = "/tmp/sms-connector-data.log"
LOG = "sms-connector-data.log"

from spam import spam

import sys
import gobject
import dbus, dbus.mainloop.glib

logfile = file(LOG, "w")
gsm, sms, sim = None, None, None
filter_engine = None

def error(message):
    sys.stderr.write("%s\n" % message)
    sys.exit(-1)

def log(message):
    logfile.write("%s\n" % message)
    logfile.flush()
    print message

def dbus_signal_handler(data, *args, **kwargs):
    signal = "%s.%s" % (kwargs["interface"], kwargs["member"])
    log('new signal %s' % (signal))

    if signal == "org.freesmartphone.GSM.SMS.IncomingMessage":
        print data, type(data)
        index = int(data)
        sender_number, contents = sim.RetrieveMessage(index)
        log('got new message from %s: %s' % (sender_number, contents))
        
        # filter SMS
        # in case of spam, just print notification
        # in a fact, this should also send dbus message to 
        # pimd, so pimd can move incoming sms into spambox
        
        is_spam = filter_engine.incoming_sms(sms_ref_number=index, 
                                   sim_number=sender_number, 
                                   text=contents)
        
        if is_spam == spam.NOT_SPAM:
            log('Cool, sms %s is not a spam' % (index))
        elif is_spam == spam.SPAM:
            log('Shit, sms %s is A spam' % (index))
    else:
        log('unhandled signal')

def init_dbus():
    """initialize dbus"""
    print "trying to get bus...",
    try:
        bus = dbus.SystemBus()
    except Exception, e:
        error("Can't connect to dbus: %s" % e)
    print "ok"
    return bus

def init_ogsmd(bus):
    """initialize ogsmd"""
    print "trying to get gsm object...",
    try:
        global gsm, sms, sim
        gsm = bus.get_object("org.freesmartphone.ogsmd", "/org/freesmartphone/GSM/Device")
        sms = bus.get_object("org.freesmartphone.ogsmd", "/org/freesmartphone/GSM/SMS")
        sim = bus.get_object("org.freesmartphone.ogsmd", "/org/freesmartphone/GSM/SIM")
    except Exception, e:
        error("can't connect to org.freesmartphone.ogsmd: %s" % e)

    bus.add_signal_receiver(dbus_signal_handler, None, None, "org.freesmartphone.ogsmd", None,
        sender_keyword = "sender", destination_keyword = "destination",
        interface_keyword = "interface", member_keyword = "member", path_keyword = "path")
    print "ok"

    return False # don't call me again


#----------------------------------------------------------------------------#

dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
mainloop = gobject.MainLoop()
bus = init_dbus()
gobject.idle_add(init_ogsmd, bus)

filter_engine = spam.SpamEngine()

try:
    mainloop.run()
except KeyboardInterrupt:
    mainloop.quit()
else:
    print "normal exit."
    filter_engine.exit()
    sys.exit(0)

